Page({
  data: {
    oldPhone: '',
    newPhone: '',
    verifyCode: '',
    countdown: 0
  },

  onLoad() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({
      oldPhone: userInfo.phone || ''
    });
  },

  onOldPhoneChange(e) {
    this.setData({
      oldPhone: e.detail.value
    });
  },

  onNewPhoneChange(e) {
    this.setData({
      newPhone: e.detail.value
    });
  },

  onVerifyCodeChange(e) {
    this.setData({
      verifyCode: e.detail.value
    });
  },

  startCountdown() {
    let count = 60;
    this.setData({ countdown: count });
    this.countdownTimer = setInterval(() => {
      count--;
      if (count <= 0) {
        clearInterval(this.countdownTimer);
      }
      this.setData({ countdown: count });
    }, 1000);
  },

  sendVerifyCode() {
    const { oldPhone } = this.data;
    if (!oldPhone || !/^1\d{10}$/.test(oldPhone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'https://api.example.com/send-verify-code',
      method: 'POST',
      data: { phone: oldPhone },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '验证码已发送',
            icon: 'success'
          });
          this.startCountdown();
        } else {
          wx.showToast({
            title: '发送失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  submit() {
    const { oldPhone, newPhone, verifyCode } = this.data;
    
    if (!oldPhone || !newPhone || !verifyCode) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (!/^1\d{10}$/.test(newPhone)) {
      wx.showToast({
        title: '请输入正确的新手机号',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'https://api.example.com/change-phone',
      method: 'POST',
      data: {
        oldPhone,
        newPhone,
        verifyCode
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '修改失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  goBack() {
    wx.navigateBack();
  }
}); 